<template>
  <div class="login-bg">
    <img class="login-logo" src="@/assets/123.svg" alt="logo" />
    <div class="login-form-box">
      <div class="login-title">欢迎登录快营营销主营系统</div>
      <div v-if="loginErrorMsg" class="login-error-msg">{{ loginErrorMsg }}</div>
      <el-form :model="loginForm" :rules="rules" ref="formRef">
        <el-form-item prop="mobile">
          <el-input
            v-model="loginForm.mobile"
            placeholder="手机号"
            prefix-icon="el-icon-mobile"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="code">
          <div class="code-row-flex">
            <el-input
              v-model="loginForm.code"
              placeholder="验证码"
              prefix-icon="el-icon-lock"
              autocomplete="off"
              class="code-input"
            />
            <el-button @click="onSendCode" class="code-btn">获取验证码</el-button>
          </div>
          <div class="login-links-row">
            <div v-if="showRegisterTip" class="register-tip">
              没有账号？<a href="#">免费注册一个！</a>
            </div>
            <div class="forget-link"><a href="#">忘记密码？</a></div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%;" @click="onLogin">登录</el-button>
        </el-form-item>
        <div class="protocol-tip">
          登录注册即代表同意
          <a href="#" target="_blank">《快服用户协议》</a>
          <a href="#" target="_blank">《快服隐私政策》</a>
        </div>
      </el-form>
    </div>
    <img class="login-watermark" src="@/assets/123.svg" alt="watermark" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { adminLogin, sendSms, verifySmsCode } from '@/api/login'
import { useLoginEmpStore } from '@/stores/loginEmp'
import type { BaseResponse, LoginResponseData } from '@/api/model/model'

const router = useRouter()
const loginStore = useLoginEmpStore()

const loginForm = ref({
  mobile: '',
  code: ''
})

const rules = {
  mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const formRef = ref()
const loginErrorMsg = ref('')

const showRegisterTip = computed(() =>
  loginErrorMsg.value === '验证码错误，请重新获取验证码' ||
  loginErrorMsg.value === '验证码已失效，请重新获取验证码' ||
  loginErrorMsg.value.includes('账号')
)

const clearLoginError = () => {
  loginErrorMsg.value = ''
}

// 清空登录表单
const clearLoginForm = () => {
  loginForm.value.mobile = ''
  loginForm.value.code = ''
  formRef.value?.clearValidate()
}

const onSendCode = async () => {
  if (!loginForm.value.mobile) {
    ElMessage.error('请先输入手机号')
    return
  }

  console.log('📤 开始发送验证码...')
  console.log('📱 手机号:', loginForm.value.mobile)

  try {
    const response = await sendSms({ mobile: loginForm.value.mobile })
    console.log('📤 发送验证码完整响应:', response)

    // 提取响应数据
    const responseData = response.data
    console.log('📤 发送验证码响应数据:', responseData)

    if (responseData.code === '100') {
    ElMessage.success('验证码已发送')
  } else {
      console.error('❌ 发送验证码失败:', responseData)
      ElMessage.error(responseData.message || '发送失败')
    }
  } catch (error) {
    console.error('❌ 发送验证码异常:', error)
    ElMessage.error('发送失败，请重试')
  }
}

const onLogin = async () => {
  clearLoginError()
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    try {
      console.log('🔐 开始登录流程...')
      console.log('📱 登录表单数据:', loginForm.value)

      // 先验证验证码
      console.log('📱 步骤1: 验证验证码...')
      const verifyResponse = await verifySmsCode({
        mobile: loginForm.value.mobile,
        code: loginForm.value.code
      })

      console.log('📱 验证码验证完整响应:', verifyResponse)
      const verifyData = verifyResponse.data
      console.log('📱 验证码验证响应数据:', verifyData)

      if (verifyData.code !== '100') {
        if (verifyData.code === '906') {
          loginErrorMsg.value = '验证码错误，请重新获取验证码'
        } else if (verifyData.message?.includes('失效')) {
          loginErrorMsg.value = '验证码已失效，请重新获取验证码'
        } else {
          loginErrorMsg.value = verifyData.message || '验证码错误，请重新获取验证码'
        }
        return
      }
      console.log('✅ 验证码验证成功')

      // 验证码正确，进行登录
      console.log('🚀 步骤2: 开始登录...')
      const loginResponse = await adminLogin({
        mobile: loginForm.value.mobile,
        code: loginForm.value.code
      })

      console.log('🚀 登录完整响应:', loginResponse)
      const loginData = loginResponse.data
      console.log('🚀 登录响应数据:', loginData)

      if (loginData.code === '100') {
        loginErrorMsg.value = ''
        // 构造完整的登录信息对象，适配新接口
        const loginInfo = {
          token: loginData.data.token,
          user: loginData.data.user
        }
        console.log('💾 保存登录信息:', loginInfo)
        loginStore.setLoginEmp(loginInfo)
        ElMessage.success('登录成功')
        console.log('🔄 跳转到控制台页面...')
        router.push('/control')
        clearLoginForm()
      } else if (loginData.code === '902') {
        loginErrorMsg.value = '登录失败'
      } else if (loginData.message?.includes('禁用')) {
        loginErrorMsg.value = '该账号已禁用，无法登陆'
      } else {
        loginErrorMsg.value = loginData.message || '登录失败'
      }
    } catch (error) {
      console.error('❌ 登录过程发生错误:', error)
      loginErrorMsg.value = '登录失败，请重试'
    }
  })
}
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  background: #f5f7fa;
  position: relative;
}
.login-logo {
  position: absolute;
  top: 32px;
  left: 32px;
  width: 40px;
  height: 40px;
}
.login-form-box {
  width: 420px;
  margin: 0 auto;
  position: absolute;
  left: 0; right: 0; top: 20%;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.10);
  padding: 56px 40px 40px 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.login-title {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 40px;
  text-align: center;
}
.code-row-flex {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
}
.code-input {
  flex: 1;
  margin-right: 8px;
}
.code-btn {
  width: 120px;
  min-width: 100px;
  height: 44px;
  font-size: 17px;
  padding: 0;
}
.login-watermark {
  position: absolute;
  right: 40px;
  bottom: 40px;
  width: 220px;
  opacity: 0.06;
  pointer-events: none;
  user-select: none;
}
.login-error-msg {
  color: #e53935;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  text-align: center;
}
.login-links-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 8px;
  font-size: 14px;
}
.register-tip {
  color: #666;
}
.register-tip a {
  color: #409eff;
  text-decoration: none;
  margin-left: 2px;
}
.forget-link a {
  color: #409eff;
  text-decoration: none;
}
.protocol-tip {
  color: #b0b0b0;
  font-size: 12px;
  text-align: center;
  margin-top: 8px;
}
.protocol-tip a {
  color: #409eff;
  margin: 0 2px;
  text-decoration: none;
}
.el-input__wrapper,
.el-input input {
  font-size: 17px;
  height: 44px;
}
</style>
